<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebRTC to DASH Live Streaming</title>
    <style>
        video {
            width: 50%;
            height: 30%;
        }
    </style>
</head>
<body>
<h1>WebRTC to DASH Live Streaming Demo</h1>
<button id="startButton">Start Streaming</button>
<div style="float: left;">
    <video id="localVideo" autoplay></video>
</div>
<div style="float: left;">
    <video id="remoteVideo" controls></video>
</div>
<script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>
<script>
    const localVideo = document.getElementById('localVideo');
    const remoteVideo = document.getElementById('remoteVideo');
    const startButton = document.getElementById('startButton');

    let localStream;
    let socket;
    let pc;

    async function startStream() {
        try {
            // 获取摄像头视频流
            localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
            localVideo.srcObject = localStream;

            // 创建 RTCPeerConnection
            pc = new RTCPeerConnection();

            // 添加本地流
            localStream.getTracks().forEach(track => pc.addTrack(track, localStream));

            // 连接到 WebSocket 服务器
            socket = io('ws://192.168.2.20:8081');

            // 发送 offer
            pc.createOffer().then(offer => pc.setLocalDescription(offer))
                .then(() => socket.emit('offer', JSON.stringify(pc.localDescription)));

            // 监听 ICE 候选
            pc.onicecandidate = event => {
                if (event.candidate) {
                    socket.emit('candidate', JSON.stringify(event.candidate));
                }
            };

            // 接收 answer 和 candidate
            socket.on('answer', answer => {
                pc.setRemoteDescription(new RTCSessionDescription(JSON.parse(answer)));
            });

            socket.on('candidate', candidate => {
                pc.addIceCandidate(new RTCIceCandidate(JSON.parse(candidate)));
            });

            // 设置远程视频播放器
            pc.ontrack = event => {
                remoteVideo.srcObject = event.streams[0];
            };

            // 开始流媒体
            socket.emit('startStream', { sessionId: socket.id });
        } catch (err) {
            console.error('Error accessing media devices.', err);
        }
    }

    startButton.addEventListener('click', startStream);
</script>
</body>
</html>